﻿using System;
using System.Text;

namespace PowerShellCustomTool
{
    public static class PowerShellExtensions
    {
        public static string InvokePowerShell(this string theInput, out string fileExtension)
        {
            var sb = new StringBuilder();

            object extension = null;
            try
            {
                PowerShellUtil.ThePowerShellEngine().AddScript(theInput);
                var results = PowerShellUtil.ThePowerShellEngine().Invoke();

                if (PowerShellUtil.ThePowerShellEngine().Streams.Error.Count > 0)
                {
                    foreach (var item in PowerShellUtil.ThePowerShellEngine().Streams.Error)
                    {
                        sb.AppendLine(item.Exception.Message);
                        sb.AppendLine(item.InvocationInfo.PositionMessage);
                    }
                }
                else
                {
                    extension = PowerShellUtil.TheRunspace().SessionStateProxy.GetVariable("extension");

                    foreach (var item in results)
                    {
                        sb.AppendLine(item.ImmediateBaseObject.ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                sb.AppendLine(ex.Message);
            }

            if (extension != null)
            {
                fileExtension = string.IsNullOrEmpty(extension.ToString()) ? ".cs" : "." + extension;
            }
            else
            {
                fileExtension = "";
            }

            return sb.ToString();
        }
    }
}